//
//  MainViewController.swift
//  Weibo
//
//  Created by niqiang on 16/6/30.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit
import SVProgressHUD

//主控制器
class WBMainViewController: UITabBarController {
    
    // 定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViewControllers()
        setupComposeButton()
        setupTimer()
        
        //设置新特性视图
        setupNewfeatureViews()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default().addObserver(self, selector: #selector(userLogin), name: WBUserShouldLoginNotification, object: nil)
        
        //测试未读数量
        WBNetworkManager.shared.unreadCount{ (count) in
            print("有\(count)条新微博")
        }
    }
    
    deinit {
        //销毁时钟
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default().removeObserver(self)
    }
    
    //MARK:设置竖屏
    //设置竖屏  portrait：竖屏 （肖像） landscape:横屏
    //注意 设置后 当前控制器及其子控制器都遵循这个方向
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .portrait
    }
    
    //MARK: - 监听方法
    @objc private func userLogin(n: Notification) {
        print("用户登录通知\(n)")
//        
//        // 展现登录控制器  一般和UINavigationController连用，方便返回
//        
//        let nav = UINavigationController(rootViewController: WBOAuthViewController())
        
//        present(nav, animated: true, completion: nil)
        var when = DispatchTime.now()
        //判断n.object 是否有值 ->token过期，提示用户重新登录
        if n.object != nil {
            //设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            //修改延时时间
            when = DispatchTime.now() + 2
        }
        DispatchQueue.main.after(when: when) {
        SVProgressHUD.setDefaultMaskType(.clear)
            //展现登录控制器 - 通常和导航控制器连用 ，方便返回
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    //MARK: - tabbar中部按钮监听方法
    //@objc 的作用 允许这个函数在“运行时” 通过OC的消息机制被调用
    @objc private func composeStatus() -> () {
        print("写微博")
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.green()
        
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
        
        
    }
    
}

//MARK: - 私有控件
//撰写按钮
private var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

//MARK: - 新特性视图处理
extension WBMainViewController{

//设置新特性视图
    private func setupNewfeatureViews() {
    
        //0.判断是否登录
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        //1.如果更新，显示新特性，否则显示欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        //2.添加视图
//        v.frame = view.bounds
        
        view.addSubview(v)
    }
    //构造函数： 给属性分配空间
    //extention 中可以有计算型属性，不会占用储存空间
    private var isNewVersion: Bool{
        
        //1.取当前的版本号1.0.2
//        print(Bundle.main().infoDictionary)
        let currentVersion = Bundle.main().infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)
        
        //2.取保存在“Dociment” 目录中的之前的版本号“1.0.2”
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print("沙盒版本" + sandboxVersion)
    
        //3.将当前版本号保存在沙盒1.0.2
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //4.返回两个版本号“是否一致” not new
        
        return currentVersion != sandboxVersion
//        return currentVersion == sandboxVersion
        
    }
}

//MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate{
    
    //代理方法：将要选择TabBarItem （实现再次点击TabBarItem刷新）
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //        print("将要切换到\(viewController)")
        
        //1.获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //2.判断当前索引是首页，同时idx也是首页，重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex  {
            print("点击首页")
            //3.让表格滚动到顶部
            //a.获取控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            //b.滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            //4.刷新数据 - 增加延迟，是保证保证表格先滚动到顶部在刷新
            DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            // 5.清除tabItem 的badgeNumber （<小红点显示有多少新微博>当我们点击首页刷新后 小红点应该消失）
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared().applicationIconBadgeNumber = 0
        }
        
        
        // 判断目标控制器是否是UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
    
}


//MARK: - 时钟相关方法
extension WBMainViewController {
    
    //定义时钟
    private func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    // 时钟触发方法
    @objc private func updateTimer(){
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            print("检测到\(count)条微博")
            
            //设置首页 tabBarItem 的 badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置APP的badgeNumber，从iOS 8.0之后，要用户授权后才能够显示
            UIApplication.shared().applicationIconBadgeNumber = count
        }
    }
}

//MARK: - 设置界面
extension WBMainViewController {
    
    //设置中部撰写按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的高度
        let count = CGFloat(childViewControllers.count)
        
        //将向内缩进的宽度
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //添加监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    //设置所有子控制器
    private func setupViewControllers() {
        
        //——————————————————
        //        let array: [[String: AnyObject]] = [
        //            ["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo": ["imageName": "","message": "关注一些人，回这里看看有什么惊喜"]],
        //            ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，别人评论你的微博，给你发的消息，都会在这里收到消息"]],
        //            ["clsName":"UIViewController"],
        //            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，最新，最热微博尽在掌握，不再会与事实潮流擦肩而过"]],
        //            ["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorInfo": ["imageName": "visitordiscover_image_profile","message": "登录后，你的微博，相册，个人资料会显示在这里，展示给别人"]],
        //            ]
        
        //测试
        //(array as NSArray).write(toFile: "/Users/mac/Desktop/demo.plist", atomically: true)
        //        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        //        (data as NSData).write(toFile: "/Users/niqiang/Desktop/demo.json", atomically: true)
        
        
        //——————————————从bundle加载配置的json
        //1.路径 、2.加载NSData 3.反序列化转换成数组
        //        guard let path = Bundle.main().pathForResource("main.json", ofType: nil),
        //            data = NSData(contentsOfFile: path),
        //            array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: AnyObject]]
        //            else {
        //                return
        //        }
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //1.加载deta
        var data = NSData(contentsOfFile: jsonPath)
        //判断data是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            //从Bundle加载data
            let path = Bundle.main().pathForResource("main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
            
        }
        
        //反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                return
        }
        
        
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            
            arrayM.append(viewController(dict: dict ))
            
        }
        
        //设置tabBat的子控制器
        viewControllers = arrayM
        
    }
    
    private func viewController(dict: [String: AnyObject]) -> UIViewController {
        
        //1.获取字典内容
        guard let clsName = dict["clsName"] as? String,
            title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
            cls = NSClassFromString(Bundle.main().namespace + "." + clsName) as? WBBaseViewController.Type,
            visitorDict = dict["visitorInfo"] as? [String: String]
            
            else {
                return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        //设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        //tabbar设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar的标题字体、大小
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange()],for: .highlighted)
        //系统默认是12号字体
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        //实例化导航控制器时，会调用push方法rootVC压栈
        let nav =  WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
